﻿using System.Collections;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text.RegularExpressions;
using System.Web.Mvc;

namespace BellAssistant.WebAPI.Common
{
    public class CommonHelper
    {
        public static ActionResult GetActionResult(object data)
        {
            return new JsonResult() { Data = data, JsonRequestBehavior = JsonRequestBehavior.AllowGet, MaxJsonLength = 2147483647 };
        }

        //取卡管返回信息的正则匹配
        public static string GetMatchResult(string key, string inputStr)
        {
            string regexStr = string.Format(@"(<{0}>)(.+)(</{1}>|<{2}>)", key, key, key);
            Regex regex = new Regex(regexStr, RegexOptions.Compiled | RegexOptions.Multiline);
            MatchCollection mc = regex.Matches(inputStr);
            ArrayList mcArray = new ArrayList();
            foreach (Match match in mc)
            {
                mcArray.Add(match.Groups[2]);
            }
            if (mcArray.Count > 0)
            {
                return mcArray[0].ToString().Trim();
            }
            else
            {
                return string.Empty;
            }
        }


        /// <summary>
        /// Convert Image to Byte[]
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public static byte[] ImageToBytes(Image image)
        {
            ImageFormat format = image.RawFormat;
            using (MemoryStream ms = new MemoryStream())
            {
                if (format.Equals(ImageFormat.Jpeg))
                {
                    image.Save(ms, ImageFormat.Jpeg);
                }
                else if (format.Equals(ImageFormat.Png))
                {
                    image.Save(ms, ImageFormat.Png);
                }
                else if (format.Equals(ImageFormat.Bmp))
                {
                    image.Save(ms, ImageFormat.Bmp);
                }
                else if (format.Equals(ImageFormat.Gif))
                {
                    image.Save(ms, ImageFormat.Gif);
                }
                else if (format.Equals(ImageFormat.Icon))
                {
                    image.Save(ms, ImageFormat.Icon);
                }
                byte[] buffer = new byte[ms.Length];
                //Image.Save()会改变MemoryStream的Position，需要重新Seek到Begin
                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(buffer, 0, buffer.Length);
                return buffer;
            }
        }
    }
}